package com.learning.dynamic.executor.config.nacos;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.ConfigService;
import com.learning.dynamic.executor.configcenter.adapter.NacosConfigCenterAdapter;
import com.learning.dynamic.executor.listener.adapter.NacosListerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;

/**
 * @author Wang Xu
 * @date 2024/3/20
 */
public class NacosConfigInitializer implements ApplicationRunner, ApplicationContextAware {
    private static ApplicationContext applicationContext;
    private static ConfigService configService;

    @Autowired
    private NacosConfigProperties nacosConfigProperties;

    public static ConfigService getConfigService() {
        return configService;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        configService = nacosConfigProperties.configServiceInstance();
        Assert.notNull(configService, "configService is null ...");

        applicationContext.getAutowireCapableBeanFactory()
                .initializeBean(new NacosListerAdapter(configService), "nacosListerAdapter");
        applicationContext.getAutowireCapableBeanFactory()
                .initializeBean(new NacosConfigCenterAdapter(configService), "nacosConfigCenterAdapter");

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        NacosConfigInitializer.applicationContext = applicationContext;
    }
}